package cashpointer.mobile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Locale;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import cashpointer.mobile.dao.DaoModel.Regions;
import cashpointer.mobile.support.Functions;
import cashpointer.mobile.support.NotificationSupportManager;
import cashpointer.mobile.support.PreferencesManager;

public class FindActivity extends Activity {
	
	/**
	 * Opcje menu.
	 */
	static private final int MENU_QUIT = Menu.FIRST;
	static private final int MENU_FIND = Menu.FIRST + 1;
	static private final int MENU_GPS = Menu.FIRST + 2;

	/**
	 * Opcje dialog.
	 */
	static private final int DIALOG_GPS_NETWORK_OFF = 1001;
	static private final int DIALOG_INTERNET_OFF = 1002;
	static private final int DIALOG_CANNOT_ESTABLISH_LOCATION = 1003;
	static private final int DIALOG_G_GEO_SERVER_ERROR = 1004;
	static private final int DIALOG_G_GEO_MISSING_QUERY = 1005;
	static private final int DIALOG_G_GEO_UNKNOWN_ADDRESS = 1006;
	static private final int DIALOG_G_GEO_UNAVAILABLE_ADDRESS = 1007;
	static private final int DIALOG_G_GEO_BAD_KEY = 1008;
	static private final int DIALOG_G_GEO_TOO_MANY_QUERIES = 1009;
	
	/**
     * The columns we are interested in from the database
     */	
	private static final String[] REGION_PROJECTION = new String[] {
    	Regions._ID, // 0
    	Regions.NAME, // 1
    };
	
	// Ustalona pozycja
	private Double gpsLatitude = null;
	private Double gpsLongitude = null;
	private LocationManager locationManager = null;
	private LocationListener locationListener = null;

	private ConnectivityManager connectivityManager = null;
	
	// Logi
	//private static final String LOG_TAG = "FindActivity";
	
	// No errors occurred; the address was successfully parsed and its geocode was returned.
    private static final String G_GEO_SUCCESS = "200";
    
    // A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is unknown.
    private static final String G_GEO_SERVER_ERROR = "500";
    
    // An empty address was specified in the HTTP q parameter.
    private static final String G_GEO_MISSING_QUERY = "601";
    
    // No corresponding geographic location could be found for the specified address, possibly because the address is relatively new, or because it may be incorrect.
    private static final String G_GEO_UNKNOWN_ADDRESS = "602";
    
    // The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.
    private static final String G_GEO_UNAVAILABLE_ADDRESS = "603";
    
    // The given key is either invalid or does not match the domain for which it was given.
    private static final String G_GEO_BAD_KEY = "610";
    
    // The given key has gone over the requests limit in the 24 hour period or has submitted too many requests in too short a period of time. If you're sending multiple requests in parallel or in a tight loop, use a timer or pause in your code to make sure you don't send the requests too quickly.
    private static final String G_GEO_TOO_MANY_QUERIES = "620";
    
	public void onResume() {
		super.onResume();

    	// Wypelnienie danymi formularza
    	fillFields();
    	
		// Ustawiam tylko dla GPS, NETWORK nie powinien zmieniac polozenia
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationListener = new MyLocationListener();
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

		// Manadzer informujacy o polaczeniu z internetem
		connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(android.R.style.Theme_Light);
        setContentView(R.layout.find);

    	// Wypelnienie danymi formularza
    	fillFields();
    	
		// Ustawiam tylko dla GPS, NETWORK nie powinien zmieniac polozenia
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationListener = new MyLocationListener();
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

		// Manadzer informujacy o polaczeniu z internetem
		connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    }
    
	/**
     * Funkcja budowania menu.
     */
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(2, MENU_FIND, 0, getString(R.string.find_determine_location_button)).setIcon(R.drawable.menu_find);
        menu.add(1, MENU_GPS, 0, getString(R.string.find_get_gps_location_button)).setIcon(R.drawable.menu_gps);
        menu.add(0, MENU_QUIT, 0, getString(R.string.menu_exit)).setIcon(R.drawable.menu_close);
        return true;
    }

    /**
     * Obsluga zdarzenia wybrania opcji z menu.
     */
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        	case MENU_QUIT: {
        		quit();
        		return true;
        	}
        	case MENU_FIND: {
        		determineLocation();
        		return true;
        	}
        	case MENU_GPS: {
        		getGPSLocation();
        		return true;
        	}
        }
	    
        return false;
    }
    
    /**
     * Tworzy okno dialogu.
     */
    protected Dialog onCreateDialog(int id) {
        Dialog dialog;
        switch(id) {
	        case DIALOG_GPS_NETWORK_OFF: {
	        	dialog = NotificationSupportManager.buildAlertDialog(this, getString(R.string.notification_gps_network_off));
	        	break;
		    }
	        case DIALOG_INTERNET_OFF: {
	        	dialog = NotificationSupportManager.buildAlertDialog(this, getString(R.string.notification_internet_off));
	        	break;
		    }
	        case DIALOG_CANNOT_ESTABLISH_LOCATION: {
	        	dialog = NotificationSupportManager.buildAlertDialog(this, getString(R.string.notification_cannot_establish_location));
	        	break;
		    }
	        case DIALOG_G_GEO_SERVER_ERROR: {
	        	dialog = NotificationSupportManager.buildAlertDialog(this, getString(R.string.notification_g_geo_server_error));
	        	break;
		    }
	        case DIALOG_G_GEO_MISSING_QUERY: {
	        	dialog = NotificationSupportManager.buildAlertDialog(this, getString(R.string.notification_g_geo_missing_query));
	        	break;
		    }
	        case DIALOG_G_GEO_UNKNOWN_ADDRESS: {
	        	dialog = NotificationSupportManager.buildAlertDialog(this, getString(R.string.notification_g_geo_unknown_address));
	        	break;
		    }
	        case DIALOG_G_GEO_UNAVAILABLE_ADDRESS: {
	        	dialog = NotificationSupportManager.buildAlertDialog(this, getString(R.string.notification_g_geo_unavailable_address));
	        	break;
		    }
	        case DIALOG_G_GEO_BAD_KEY: {
	        	dialog = NotificationSupportManager.buildAlertDialog(this, getString(R.string.notification_g_geo_bad_key));
	        	break;
		    }
	        case DIALOG_G_GEO_TOO_MANY_QUERIES: {
	        	dialog = NotificationSupportManager.buildAlertDialog(this, getString(R.string.notification_g_geo_too_many_queries));
	        	break;
		    }
	        default: {
	            dialog = null;
	        }
        }
        
        return dialog;
    }

    /**
     * Ustalenie polozenia z danych wpisanych do formularza.
     */
    private void determineLocation() {
    	// Zapisuje "Podaj miasto" dane na przyszlosc
        EditText cityEditText = (EditText)findViewById(R.id.findCityEditText);
        String city = cityEditText.getText().toString();
        if (city == null) {
        	city = "";
        }
        PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.FIND_CITY_CHOOSE, city);

        // Zapisuje "Podaj ulice" dane na przyszlosc
        EditText streetEditText = (EditText)findViewById(R.id.findStreetEditText);
        String street = streetEditText.getText().toString();
        if (street == null) {
        	street = "";
        }
        PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.FIND_STREET_CHOOSE, street);
		
        // Pobieram nazwe wojewodztwa
        String region = "";
        long regionId = PreferencesManager.getLong(getApplicationContext(), PreferencesManager.FIND_REGION_CHOOSE_ID, (long)0);
        Uri regionUri = ContentUris.withAppendedId(Regions.CONTENT_URI, regionId);
        Cursor regionCursor = managedQuery(regionUri, REGION_PROJECTION, null, null, Regions.DEFAULT_SORT_ORDER);			
        if (regionCursor != null && regionCursor.moveToFirst()) {
        	int regionNameColumn = regionCursor.getColumnIndex(Regions.NAME);

			// Pobieram wojewodztwo
			String regionSelected = regionCursor.getString(regionNameColumn);
			if (regionSelected != null && regionSelected.length() > 0) {
				region = regionSelected;
			} else {
				//Log.w(LOG_TAG, "Wojewodztwo jest niepoprawne!");	
			}
        } else {
        	//Log.w(LOG_TAG, "Kursor wojewodztwa jest bledny!");
        }
        
        // Sprawdzam, czy jest dostep do internetu
        if (Functions.isConnectionEnabled(connectivityManager)) {
        	boolean isLocationApproximate = false;
        	
        	// Budowanie zapytania URL.
            StringBuilder urlAddress = new StringBuilder();
            urlAddress.append("Polska ");
            
            // Dodanie wojewodztwa, jesli jest
            if (region != null && region.length() > 0) {
            	urlAddress.append(", ");
            	urlAddress.append(region);
            } else {
            	isLocationApproximate = true;
            }

            // Dodanie mista, jesli jest
            if (city != null && city.length() > 0) {
            	urlAddress.append(", ");
            	urlAddress.append(city);
            } else {
            	isLocationApproximate = true;
            }

            // Dodanie ulicy, jesli jest
            if (street != null && street.length() > 0) {
            	urlAddress.append(", ");
            	urlAddress.append(street);
            } else {
            	isLocationApproximate = true;
            }
            
            try {
            	// Pobieranie klucza google maps key, potrzebengo do wyswietlania mapy
                String googleKeyMaps = PreferencesManager.getString(getApplicationContext(), PreferencesManager.GOOGLE_KEY_MAPS, getString(R.string.config_default_google_key));
                
				// Czytanie strony
            	String url = "http://maps.google.pl/maps/geo?q=";
            	url += URLEncoder.encode(urlAddress.toString(), "UTF-8");
            	url += "&output=xml&oe=utf8&sensor=true&key=";
                url += googleKeyMaps;
                
            	// Pobieram strone z sieci
            	String siteBody = Functions.readSite(url);

				// Usuwam zbedne znaki dla poprawnego parsowania xml
				siteBody = siteBody.replaceAll(">\\s+<", "><");
				
				// Logi
				//Log.d(LOG_TAG, siteBody);
            	
				// Pobranie adresu pliku i wersja danych
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				factory.setIgnoringElementContentWhitespace(true);
				DocumentBuilder builder = factory.newDocumentBuilder();
				InputStream inputStream = new ByteArrayInputStream(siteBody.getBytes());
				Document parser = builder.parse(inputStream);

				// Pobieranie statusu
				String statusCode = null;
				NodeList statusNodeList = parser.getElementsByTagName("Status");
				if (statusNodeList != null && statusNodeList.getLength() > 0) {
					Node statusNode = statusNodeList.item(0); // potrzebny jest pierwszy i prawdopodobnie jedyny element o tej nazwie
					if (statusNode != null) {
						Node statusCodeNode = statusNode.getFirstChild();
						if (statusCodeNode != null) {
							Text statusCodeText = (Text) statusCodeNode.getFirstChild();
							String statusCodeString = statusCodeText.getData();
							if (statusCodeString != null) {
								statusCode = statusCodeString;
							}
						}
					}
				}
				//Log.d(LOG_TAG, "statusCode: " + statusCode);
				
				// Rozpoznanie kodu
				if (G_GEO_SUCCESS.equals(statusCode)) {
					// Dane do przekazania
					float floatGpsLatitude = (float) 0;
					float floatGpsLongitude = (float) 0;
	        		String gpsRegion = ""; // nie null, aby zapisalo sie do propertisow
	        		String gpsCountry = "";
	        		
					// Czytam region
					NodeList administrativeAreaNameNodeList = parser.getElementsByTagName("AdministrativeAreaName");
					if (administrativeAreaNameNodeList != null && administrativeAreaNameNodeList.getLength() > 0) {
						Node administrativeAreaNameNode = administrativeAreaNameNodeList.item(0); // potrzebny jest pierwszy i prawdopodobnie jedyny element o tej nazwie
						if (administrativeAreaNameNode != null) {
							Text administrativeAreaNameText = (Text) administrativeAreaNameNode.getFirstChild();
							String administrativeAreaNameString = administrativeAreaNameText.getData();
							if (administrativeAreaNameString != null) {
								gpsRegion = administrativeAreaNameString;
							}
						}
					}
					//Log.d(LOG_TAG, "gpsRegion: " + gpsRegion);
					
	            	// Czytam powiat
					NodeList subAdministrativeAreaNameNodeList = parser.getElementsByTagName("SubAdministrativeAreaName");
					if (subAdministrativeAreaNameNodeList != null && subAdministrativeAreaNameNodeList.getLength() > 0) {
						Node subAdministrativeAreaNameNode = subAdministrativeAreaNameNodeList.item(0); // potrzebny jest pierwszy i prawdopodobnie jedyny element o tej nazwie
						if (subAdministrativeAreaNameNode != null) {
							Text subAdministrativeAreaNameText = (Text) subAdministrativeAreaNameNode.getFirstChild();
							String subAdministrativeAreaNameString = subAdministrativeAreaNameText.getData();
							if (subAdministrativeAreaNameString != null) {
								gpsCountry = subAdministrativeAreaNameString;
							}
						}
					}
					//Log.d(LOG_TAG, "gpsCountry: " + gpsCountry);
	        		
	            	// Czytam polozenie
					String point = null;
					NodeList pointNodeList = parser.getElementsByTagName("Point");
					if (pointNodeList != null && pointNodeList.getLength() > 0) {
						Node pointNode = pointNodeList.item(0); // potrzebny jest pierwszy i prawdopodobnie jedyny element o tej nazwie
						if (pointNode != null) {
							Node coordinatesNode = pointNode.getFirstChild();
							if (coordinatesNode != null) {
								Text coordinatesText = (Text) coordinatesNode.getFirstChild();
								String coordinatesString = coordinatesText.getData();
								if (coordinatesString != null) {
									point = coordinatesString;
								}
							}
						}
					}
					//Log.d(LOG_TAG, "point: " + point);
					
	        		// Dziele point na polozenie
					if (point != null) {
						String[] pointArray = point.split(",");
						if (pointArray.length >= 2) {
							floatGpsLongitude = Float.parseFloat(pointArray[0]); 
							floatGpsLatitude = Float.parseFloat(pointArray[1]);
						}
					}
					
	        		// Czy polozenie zostalo ustalone, jesli nie
	        		if (floatGpsLatitude == (float)0 || floatGpsLongitude == (float)0) {
	        			throw new Exception("Pomimo statusu 200 nie ustalono polozenia!");
	        		} else {
						//Log.d(LOG_TAG, "floatGpsLatitude: " + floatGpsLatitude);
						//Log.d(LOG_TAG, "floatGpsLongitude: " + floatGpsLongitude);
	        		}
	        		
	            	// Zapisanie polozenie w pamieci
	        		PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.FIND_GPS_LATITUDE, floatGpsLatitude);
	        		PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.FIND_GPS_LONGITUDE, floatGpsLongitude);
	        		PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.FIND_GPS_REGION, gpsRegion);
	        		PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.FIND_GPS_COUNTRY, gpsCountry);
	        		
	        		// Uruchomienie activity wyszukiwarki-listy
	        		Intent intent = new Intent(this, FindedCashpointsFromLocationActivity.class);
	        		intent.putExtra(PreferencesManager.IS_LOCATION_APPROXIMATE, isLocationApproximate);
	        		startActivity(intent);
	            } else if (G_GEO_SERVER_ERROR.equals(statusCode)) {
					// Komunikat
		    		showDialog(DIALOG_G_GEO_SERVER_ERROR);
	            } else if (G_GEO_MISSING_QUERY.equals(statusCode)) {
					// Komunikat
		    		showDialog(DIALOG_G_GEO_MISSING_QUERY);
	            } else if (G_GEO_UNKNOWN_ADDRESS.equals(statusCode)) {
					// Komunikat
		    		showDialog(DIALOG_G_GEO_UNKNOWN_ADDRESS);
	            } else if (G_GEO_UNAVAILABLE_ADDRESS.equals(statusCode)) {
					// Komunikat
		    		showDialog(DIALOG_G_GEO_UNAVAILABLE_ADDRESS);
	            } else if (G_GEO_BAD_KEY.equals(statusCode)) {
					// Komunikat
		    		showDialog(DIALOG_G_GEO_BAD_KEY);
	            } else if (G_GEO_TOO_MANY_QUERIES.equals(statusCode)) {
					// Komunikat
		    		showDialog(DIALOG_G_GEO_TOO_MANY_QUERIES);
	            }	
			} catch (Exception e) {
				// Blad
				//Log.e(LOG_TAG, "Blad", e);

				// Komunikat
	    		showDialog(DIALOG_CANNOT_ESTABLISH_LOCATION);
			}	
        } else {
			// Komunikat
    		showDialog(DIALOG_INTERNET_OFF);
        }
	}

    /**
     * Pobranie polozenia z urzadzenia GPS.
     */
	private void getGPSLocation() {
		// Zmienne pomocnicze
		boolean isGPSProviderOn = false;
		boolean isNetworkProviderOn = false;
		
		// Resetuje zmienne polozenia
		gpsLatitude = null;
		gpsLongitude = null;
		
		// Sprawdzam czy urzadzenie GPS jest wlaczone
		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			// Pobieram ostatnia znana lokalizacje
			Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			if (location != null) {
				gpsLatitude = location.getLatitude();
				gpsLongitude = location.getLongitude();
				isGPSProviderOn = true;
			}
		}
		
		// Jesli nie udalo sie ustalic polozenia GPS ustalam je na podstawie NETWORK
		if (!isGPSProviderOn) {
			// Sprawdzam czy urzadzenie NETWORK jest wlaczone
			if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
				// Pobieram ostatnia znana lokalizacje
				Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
				if (location != null) {
					gpsLatitude = location.getLatitude();
					gpsLongitude = location.getLongitude();
					isNetworkProviderOn = true;
				}
			}
		}
		
		// Jesli nie udalo sie ustalic pozycji GPS i NETWORK
		if (!isGPSProviderOn && !isNetworkProviderOn) {
			// Resetuje zmienne polozenia
			gpsLatitude = null;
			gpsLongitude = null;
			
			// Komunikat
    		showDialog(DIALOG_GPS_NETWORK_OFF);
 		} else {
			// Wyszukane dane.
 			String region = "";
			String country = "";
			
			try {
				Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
				List<Address> addresses = geoCoder.getFromLocation(gpsLatitude, gpsLongitude, 1);
                if (addresses != null && addresses.size() > 0) {
                	Address address = addresses.get(0);
                	
                	// Pobieram wojewodztwo
                	String aa = address.getAdminArea();
                	if (aa != null) {
                		region = aa;
                	}
                	                	
                	// Pobieram powiat
                	String saa = address.getSubAdminArea();
                	if (saa != null) {
                		country = saa;
                	}
                }
			} catch (IOException e) {
				//Log.e(LOG_TAG, "Blad!", e);
			}

			// Zapisanie polozenie w pamieci
			float floatGpsLatitude =  Float.parseFloat(String.valueOf(gpsLatitude));
			PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.FIND_GPS_LATITUDE, floatGpsLatitude);
			float floatGpsLongitude =  Float.parseFloat(String.valueOf(gpsLongitude));
			PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.FIND_GPS_LONGITUDE, floatGpsLongitude);
			PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.FIND_GPS_REGION, region);
			PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.FIND_GPS_COUNTRY, country);
			
			// Uruchomienie activity wyszukiwarki-listy
			startActivity(new Intent(this, FindedCashpointsFromLocationActivity.class));
 		}
	}

    /**
     * Funkcja wypelnia pola zapamietamymi danymi a jesli takowych nie ma to kopiuje dane z konfiguracji.
     */
    private void fillFields() {
    	// Tworze adapter, ktory pobierze dane dla obiektu spinner
		Cursor regionChooseCursor = managedQuery(Regions.CONTENT_URI, REGION_PROJECTION, null, null, Regions.DEFAULT_SORT_ORDER);			
		SimpleCursorAdapter regionChooseAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, regionChooseCursor, new String[] {Regions.NAME}, new int[] {android.R.id.text1});
		regionChooseAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
        // Pobieram spinner "Wybierz wojewodztwo" i ustawiam jego wartosc
        Spinner regionChooseSpinner = (Spinner) findViewById(R.id.findRegionChooseSpinner);
        regionChooseSpinner.setAdapter(regionChooseAdapter);
        
        // Pobieram identyfikator zapamietanego wojewodztwa
        long regionChooseId = PreferencesManager.getLong(getApplicationContext(), PreferencesManager.FIND_REGION_CHOOSE_ID, (long)0);
        
        // Logi
        //Log.i(LOG_TAG, "Zaczytano z pamieci, FIND_REGION_CHOOSE_ID: " + regionChooseId);
        
        // Ustalam pozycje wybranego wojewodztwa
        int regionChoose = Functions.getRegionPosision((int)regionChooseId, regionChooseCursor);
        
        // Upewniam sie, ze ustalona pozycja nie wykracza poza zakres danych
        if (regionChoose > regionChooseCursor.getCount() - 1) {
        	regionChoose = 0;
        }
        
        // Zaznaczam pozycje pod warunkiem, ze jest cokolewiek na liscie
        if (regionChooseCursor.getCount() > 0) {
        	regionChooseSpinner.setSelection(regionChoose);
        }
        
        // Logi
        //Log.i(LOG_TAG, "Zaczytano z pamieci, regionChoose: " + regionChoose);
        
        // Reagowanie na wybor wojewodztwa - automatyczne zapisanie ustawien
        regionChooseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
		        long currentRegionChooseId = PreferencesManager.getLong(getApplicationContext(), PreferencesManager.FIND_REGION_CHOOSE_ID, (long)0);
				if (currentRegionChooseId != id) {
					// Zapisanie regionu pozycji i identyfikatora
					PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.FIND_REGION_CHOOSE_ID, id);

			        // Logi
			        //Log.i(LOG_TAG, "Zmiana wojewodztwa, FIND_REGION_CHOOSE_ID: " + id);
			        
					// Komunikat
					NotificationSupportManager.showToastNotification(FindActivity.this.getApplicationContext(), getString(R.string.notification_saved));
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
        });
                
        // Ustawiam zawartosc pola "Podaj miasto"
        String cityChoose = PreferencesManager.getString(getApplicationContext(), PreferencesManager.FIND_CITY_CHOOSE, ""); 
        EditText cityEditText = (EditText)findViewById(R.id.findCityEditText);
        cityEditText.setText(cityChoose);
        
        // Ustawiam zawartosc pola "Podaj ulice"
        String streetChoose = PreferencesManager.getString(getApplicationContext(), PreferencesManager.FIND_STREET_CHOOSE, ""); 
        EditText streetEditText = (EditText)findViewById(R.id.findStreetEditText);
        streetEditText.setText(streetChoose);   
        
        // Pobieram przycisk "Polozenie z formularza"
        Button findDetermineLocationButton = (Button) findViewById(R.id.findDetermineLocationButton);
        findDetermineLocationButton.setOnClickListener(new OnClickListener() {
	        public void onClick(View v) {
	        	FindActivity.this.determineLocation();
	        }
        });

        // Pobieram przycisk "Polozenie z GPS"
        Button findGetGPSLocationButton = (Button) findViewById(R.id.findGetGPSLocationButton);
        findGetGPSLocationButton.setOnClickListener(new OnClickListener() {
	        public void onClick(View v) {
	        	FindActivity.this.getGPSLocation();
	        }
        });
    }

	/**
     * Funkcja konczenia aplikacji.
     */
    private void quit() {
    	this.finish();
    }
    
	private class MyLocationListener implements LocationListener {
		public void onLocationChanged(final Location loc) {
			if (loc != null) {
				FindActivity.this.gpsLatitude = loc.getLatitude();
				FindActivity.this.gpsLongitude = loc.getLongitude();
			}
		}

		public void onProviderDisabled(final String provider) {
		}

		public void onProviderEnabled(final String provider) {
		}

		public void onStatusChanged(final String provider, final int status, final Bundle extras) {
		}
	}
}